#include <cairo.h>
#include <gtk/gtk.h>
#include <math.h>


static gboolean
on_expose_event(GtkWidget *widget,
    GdkEventExpose *event,
    gpointer data)
{
  cairo_t *cr;
  cr = gdk_cairo_create(widget->window);

  static gboolean xdirection = TRUE;

  int width, height;
  gtk_window_get_size(GTK_WINDOW(widget), &width, &height);

  static gdouble rotate = 0;

  static gint bigx = 20;
  static gint bigy = 200;
  static gint delta = 1;


  if (bigx > width) {
      xdirection = FALSE;
      delta = -delta;
      bigx = width;
  }

  if (bigx < 1) {
      bigx = 1;
      delta = -delta; 
  }

  if (bigy > height) {
      xdirection = TRUE;
      delta = -delta;
      bigy = height;
  }

  if (bigy < 1) {
      delta = -delta; 
      bigy = 1;
  }

  if (xdirection) {
      bigx += delta;
  } else {
      bigy += delta;
  }

  cairo_translate(cr, width / 2, height /2);

  cairo_rectangle(cr, -bigx/2, -bigy/2, bigx-2, bigy-2);
  cairo_set_source_rgb(cr, 0, 0, 0);
  cairo_set_line_width(cr, 1);  
  cairo_stroke(cr);

  cairo_rotate(cr, rotate);
  rotate += 0.01;

  cairo_rectangle(cr, -50, -25, 100, 50);
  cairo_stroke(cr);

  GdkRectangle bigrect;
  GdkRectangle rect;
  GdkRectangle intersect;

  bigrect.x = -bigx/2;
  bigrect.y = -bigy/2;
  bigrect.width = bigx -2;
  bigrect.height = bigy -2;

  rect.x = -50;
  rect.y = -25;
  rect.width = 100;
  rect.height = 50;

  gdk_rectangle_intersect(&bigrect, &rect, &intersect);
  cairo_rectangle(cr, intersect.x, intersect.y, intersect.width, intersect.height);
  cairo_fill(cr); 

  cairo_destroy(cr);

  return FALSE;
}

static gboolean
time_handler (GtkWidget *widget)
{
  if (widget->window == NULL) return FALSE;
  gtk_widget_queue_draw(widget);
  return TRUE;
}

int
main (int argc, char *argv[])
{

  GtkWidget *window;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  g_signal_connect(G_OBJECT(window), "expose-event",
      G_CALLBACK(on_expose_event), NULL);
  g_signal_connect(G_OBJECT(window), "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 250, 200); 

  gtk_widget_set_app_paintable(window, TRUE);
  gtk_widget_show_all(window);
  g_timeout_add(5, (GSourceFunc) time_handler, (gpointer) window);

  gtk_main();

  return 0;
}
